---
title: Last N Session Messages
---

This example demonstrates how to configure agents to search through previous sessions and limit the number of historical sessions included in context. This helps manage context length while maintaining relevant conversation history.

## Code

```python last_n_session_messages.py
import os

from agno.agent import Agent
from agno.db.sqlite import SqliteDb
from agno.models.openai import OpenAIChat

# Remove the tmp db file before running the script
os.remove("tmp/data.db")

agent = Agent(
    model=OpenAIChat(id="gpt-5-mini"),
    user_id="user_1",
    db=SqliteDb(db_file="tmp/data.db"),
    add_history_to_context=True,
    num_history_runs=3,
    search_session_history=True,  # allow searching previous sessions
    num_history_sessions=2,  # only include the last 2 sessions in the search to avoid context length issues
)

session_1_id = "session_1_id"
session_2_id = "session_2_id"
session_3_id = "session_3_id"
session_4_id = "session_4_id"
session_5_id = "session_5_id"

agent.print_response("What is the capital of South Africa?", session_id=session_1_id)
agent.print_response("What is the capital of China?", session_id=session_2_id)
agent.print_response("What is the capital of France?", session_id=session_3_id)
agent.print_response("What is the capital of Japan?", session_id=session_4_id)
agent.print_response(
    "What did I discuss in my previous conversations?", session_id=session_5_id
)  # It should only include the last 2 sessions
```

## Usage

<Steps>
  <Snippet file="create-venv-step.mdx" />

  <Step title="Install libraries">
    ```bash
    pip install -U agno openai
    ```
  </Step>

  <Step title="Export your OpenAI API key">

    <CodeGroup>

    ```bash Mac/Linux
      export OPENAI_API_KEY="your_openai_api_key_here"
    ```

    ```bash Windows
      $Env:OPENAI_API_KEY="your_openai_api_key_here"
    ```
    </CodeGroup> 
  </Step>

  <Step title="Create a Python file">
    Create a Python file and add the above code.
    ```bash
    touch last_n_session_messages.py
    ```
  </Step>

  <Step title="Run Agent">
    <CodeGroup>
    ```bash Mac
    python last_n_session_messages.py
    ```
    
    ```bash Windows  
    python last_n_session_messages.py
    ```
    </CodeGroup>
  </Step>

  <Step title="Find All Cookbooks">
  Explore all the available cookbooks in the Agno repository. Click the link below to view the code on GitHub:

  <Link href="https://github.com/agno-agi/agno/tree/main/cookbook/agents/state" target="_blank">
    Agno Cookbooks on GitHub
  </Link>
</Step>
</Steps>